package com.ruoyi.common.web.core;

import com.ruoyi.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.LocaleResolver;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 获取请求头国际化信息
 *
 * @author Lion Li
 */
@Slf4j
public class I18nLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String language = httpServletRequest.getHeader("content-language");
        if (StringUtils.isEmpty(language)) {
            language = httpServletRequest.getHeader("Accept-Language");
        }
        if (StringUtils.isEmpty(language)) {
            language = httpServletRequest.getHeader("lang");
        }
        Locale locale = Locale.CHINA;
        if (language != null && !language.isEmpty()) {
            log.info("请求头国际化信息为:{}", language);
            String[] split = language.split("_");
            if (split.length == 2) {
                locale = new Locale.Builder()
                    .setLanguage(split[0]) // 设置语言代码
                    .setRegion(split[1])   // 设置地区/国家代码
                    .build();          // 创建Locale实例
            }
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}
